import json

from flask import Flask, request, redirect, url_for, render_template, jsonify, flash
from spiders.config import SECRET_KEY
from spiders.db.DatabaseService import DatabaseService

app = Flask(__name__)
app.config['SECRET_KEY'] = SECRET_KEY

db_service = DatabaseService()

@app.route('/')
@app.route('/tasks', methods=['GET'])
def index():
    tasks = db_service.get_all_tasks()
    return render_template('index.html', tasks=tasks)

@app.route('/tasks/edit/<int:task_id>', methods=['GET', 'POST'])
def edit_task(task_id):
    task = db_service.get_task(task_id)
    sources = db_service.get_all_sources()

    if request.method == 'POST':
        task_data = {
            'source_id': request.form.get('source_id'),
            'source_name': request.form.get('source_name'),
            'source_book_id': request.form.get('source_book_id'),
            'cat_id': request.form.get('cat_id'),
            'book_name': request.form.get('book_name'),
            'author_name': request.form.get('author_name'),
            'task_status': int(request.form.get('task_status')),
            'exc_count': int(request.form.get('exc_count'))
        }
        try:
            db_service.update_task(task_id, task_data)
            return redirect(url_for('index'))
        except ValueError:
            flash('任务不存在', 'error')

    return render_template('edit_task.html', task=task, sources=sources)

@app.route('/tasks/delete/<int:task_id>', methods=['POST'])
def delete_task(task_id):
    try:
        db_service.delete_task(task_id)
        flash('任务删除成功', 'success')
    except ValueError:
        flash('任务不存在', 'error')
    return redirect(url_for('index'))

@app.route('/tasks/create', methods=['GET', 'POST'])
def create_task():
    if request.method == 'POST':
        task_data = {
            'source_id': request.form['source_id'],
            'source_book_id': request.form['source_book_id'],
            'cat_id': request.form['cat_id'],
            'book_name': request.form['book_name'],
            'author_name': request.form['author_name'],
            'task_status': int(request.form['task_status']),
            'exc_count': int(request.form['exc_count'])
        }
        db_service.add_task(task_data)
        return redirect(url_for('index'))

    sources = db_service.get_all_sources()
    return render_template('create_task.html', sources=sources)

@app.route('/sources')
def list_sources():
    sources = db_service.get_all_sources()
    return render_template('list_sources.html', sources=sources)

@app.route('/source/create', methods=['GET', 'POST'])
def create_source():
    if request.method == 'POST':
        source_data = {
            'source_name': request.form['source_name'],
            'crawl_rule': request.form['crawl_rule'],
            'source_status': int(request.form['source_status'])
        }
        db_service.add_source(source_data)
        return redirect(url_for('list_sources'))

    return render_template('create_source.html')

@app.route('/source/<int:source_id>/edit', methods=['GET', 'POST'])
def edit_source(source_id):
    source = db_service.get_source(source_id)
    if request.method == 'POST':
        source_data = {
            'source_name': request.form.get('source_name'),
            'source_status': int(request.form.get('source_status')),
            'crawl_rule': json.dumps({
                'bookListUrl': request.form.get('book_list_url'),
                'bookIdPattern': request.form.get('book_id_pattern'),
                'pagePattern': request.form.get('page_pattern'),
                'bookDetailUrl': request.form.get('book_detail_url'),
                'bookNamePattern': request.form.get('book_name_pattern'),
                'authorNamePattern': request.form.get('author_name_pattern'),
                'picUrlPattern': request.form.get('pic_url_pattern'),
                'descStart': request.form.get('desc_start'),
                'descEnd': request.form.get('desc_end'),
                'bookIndexUrl': request.form.get('book_index_url'),
                'indexIdPattern': request.form.get('index_id_pattern'),
                'indexNamePattern': request.form.get('index_name_pattern'),
                'bookContentUrl': request.form.get('book_content_url'),
                'contentStart': request.form.get('content_start'),
                'contentEnd': request.form.get('content_end')
            })
        }
        try:
            db_service.update_source(source_id, source_data)
            return redirect(url_for('list_sources'))
        except ValueError:
            flash('爬虫源不存在', 'error')

    rules = json.loads(source.crawl_rule) if source.crawl_rule else {}
    return render_template('edit_source.html', source=source, rules=rules)

@app.route('/source/delete/<int:source_id>', methods=['POST'])
def delete_source(source_id):
    try:
        db_service.delete_source(source_id)
        flash('爬虫源已成功删除。', 'success')
    except ValueError:
        flash('未找到指定的爬虫源。', 'error')
    return redirect(url_for('list_sources'))

@app.route('/source/<int:source_id>/rules', methods=['GET'])
def get_source_rules(source_id):
    source = db_service.get_source(source_id)
    if not source:
        return jsonify({"error": "Source not found"}), 404
    rules = json.loads(source.crawl_rule) if source.crawl_rule else {}
    return jsonify(rules)

if __name__ == '__main__':
    app.run(debug=True)
